package uk.ac.strath.cis.metric_spaces.parsers;

import java.io.Reader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import uk.ac.strath.cis.collections.ITree.Tree;
import uk.ac.strath.cis.metric_spaces.framework.Parser;

/**
 * @author Robert
 *
 */
public class DomParser implements Parser<Tree> {

    /* (non-Javadoc)
     * @see uk.ac.strath.cis.rmoss.metric_spaces.framework.Parser#parse(java.io.Reader)
     */
    public Tree parse(Reader r) throws Exception {

        DocumentBuilder db = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = db.parse(new InputSource(r));
        return parse(doc.getDocumentElement());
    }

    private Tree parse(Node node) throws Exception {
        NodeList children = node.getChildNodes();
        Tree n = new Tree();
        n.setNodeName(node.getNodeName());
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i).getNodeType() != Node.TEXT_NODE) {
                Tree child = parse(children.item(i));
                n.addChild(child);
            }
        }
        return n;
    }
}
